package com.scalar.chiptrack.adaptor.vis;

import com.scalar.chiptrack.jobs.JobHandler;
import com.scalar.chiptrack.adaptor.AdaptorConstants;
import com.scalar.chiptrack.adaptor.AdaptorUtils;
import com.scalar.chiptrack.adaptor.dao.AdaptorRunInfo;
import com.scalar.chiptrack.utils.Logger;
import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.chiptrack.utils.DateUtil;
import com.scalar.chiptrack.users.VendorAdaptor;
import com.scalar.chiptrack.users.dao.AdaptorSetUpDAO;
import com.scalar.ScalarException;

import java.io.BufferedInputStream;
import java.util.Calendar;

import HTTPClient.HTTPConnection;
import HTTPClient.HTTPResponse;
import HTTPClient.CookieModule;
import HTTPClient.NVPair;


/**
 * User: ChandraSekhar
 * Date: Aug 2, 2007
 * Time: 2:58:32 PM
 */
public class VISAdaptor extends JobHandler implements AdaptorConstants
{
    private static final String PROTOCOL_HTTP           = "http";
    private static final String HOST                    = "online.vis.com.tw";
    private static final String GET_PORTAL              = "/online/login.do?method=list";
    private static final String POST_LOGIN_URL          = "/j2ee/Main/jsp/index.jsp";
    private static final String GET_WIP_STATUS          = "/online/wip.do"; //"/j2ee/MS/jsp/index.jsp?ContentArea=MS&Locator=WIP";
    private static final String GET_REAL_WIP_STATUS     = "/online/realtimeWip.do";
    private static final String GET_SHIP_STATUS         = "/online/sn.do";
    private static final String LOG_OUT                 = "/online/login.do?method=logout";
    private static final int DEFAULT_PORT               = 80;

    public static final String FILE_NAME_SHIP_STATUS        = "VIS_SHIP_STATUS";
    public static final String FILE_NAME_WIP_STATUS         = "VIS_WIP_STATUS";
    public static final String FILE_NAME_REAL_WIP_STATUS    = "VIS_REAL_WIP_STATUS";    
    public static final String ADAPTOR_NAME                 = "VIS_FAB";

    private String m_dataOutputDir      = null;
    private Logger m_adaptorLogger      = null;
    private String m_username           = null;
    private String m_password           = null;
    private String m_accountNo          = null;
    private String m_accHashValue       = null;
    private int    m_adaptor_id         = -1;

    public VISAdaptor() throws Exception
    {
       try
        {
            VendorAdaptor vendorAdaptor = AdaptorSetUpDAO.getVendorAdaptorDetailsByVendorNameAndLocation( VENDOR_NAME_VIS, WIP_TYPE_FAB );

            if( vendorAdaptor == null )
            {
                log( "ERROR!! ERROR!! ERROR!! Exception while loading VIS Adaptor Username, Password details from database" );
                throw new ScalarException( "Exception while loading VIS Adaptor Username, Password details from database" );
            }

            m_username = vendorAdaptor.getUserId().trim();
            m_password = vendorAdaptor.getPassWord().trim();
            m_dataOutputDir = vendorAdaptor.getOutPutDirectory().trim();
            m_accHashValue  = vendorAdaptor.getCustomerId().split("#")[1];
            m_accountNo     = vendorAdaptor.getCustomerId().split("#")[0];

            if ( m_dataOutputDir != null )
            {
                if ( m_dataOutputDir.endsWith( "/" ) || m_dataOutputDir.endsWith( "\\" ) )
                {
                    m_dataOutputDir = m_dataOutputDir + m_username;
                }
                else
                {
                    m_dataOutputDir = m_dataOutputDir + "/" + m_username;
                }

                AdaptorUtils.makeAllAdaptorDirs( m_dataOutputDir );
                m_adaptorLogger = AdaptorUtils.getAdaptorLogger( m_dataOutputDir , VENDOR_NAME_VIS);
                AdaptorUtils.setLogger( m_adaptorLogger );
            }
        }
        catch ( Exception se )
        {
            log( "ERROR!! ERROR!! ERROR!! Exception while loading VIS Adaptor Username, Password details from database, Exception: " + se );
            throw new ScalarException( "Exception while loading VIS Adaptor Username, Password details from database" );
        }

       // m_observer = new UTACHtmlObserver();
    }

    public static void main( String[] args ) throws Exception
    {
        new VISAdaptor().execute();
    }

    public void execute() throws Exception
    {
        try
        {
            m_adaptor_id = AdaptorRunInfo.saveAdaptorLastUpdatedStatus( CONSTANT_ADAPTOR, ADAPTOR_NAME, CONSTANT_SUCCESS, -1);

            // Step 1
            // prints the version of Adaptor
            AdaptorUtils.printHeader(VENDOR_NAME_VIS, CONSTANT_ADAPTOR );

            // Step 2
            // removes the old files out side done directory
           AdaptorUtils.removeOldFiles(m_dataOutputDir, m_adaptorLogger);


            HTTPConnection connection = login( HOST, DEFAULT_PORT, m_username, m_password );

            if ( connection != null )
            {
                BufferedInputStream bfReader = null;

                //For DownLoading Real Time WipStatus Report
                HTTPResponse rsp = requestRealTimeWipStatusReport( connection );

                if( rsp != null )
                {
                    bfReader = new BufferedInputStream( rsp.getInputStream()  );
                    if( bfReader != null )
                    {
                        System.out.println( "\tDownloading the Real Time Wip Status Sheet..." );
                        log( "\tDownloading the Real Time Wip Status Sheet..." );
                        AdaptorUtils.saveAsBinaryFile( bfReader, m_dataOutputDir, FILE_NAME_REAL_WIP_STATUS, FILE_EXTN_CSV,true );
                        if ( m_adaptor_id > 0 )
                        {
                            AdaptorRunInfo.saveAdaptorFileInfo( m_adaptor_id , FILE_NAME_REAL_WIP_STATUS, FILE_EXTN_CSV, StringUtils.formatDateandTime(DateUtil.getFormattedTimeStamp() )) ;
                        }
                    }
                    else
                    {
                        log( "Could not save Real Time Sheet from Buffer Reader" );
                        throw new ScalarException( "Could not save Real Time Wip Status Sheet from Buffer Reader" );
                    }
                }
                else
                {
                    log( "Could not create response object of Real Time Wip Status Sheet" );
                    throw new ScalarException( "Could not create response object of Real Time Wip Status Sheet" );
                }

                //For DownLoading WipStatus Report
                rsp = requestWipStatusReport( connection );

                if( rsp != null )
                {
                    bfReader = new BufferedInputStream( rsp.getInputStream()  );
                    if( bfReader != null )
                    {
                        System.out.println( "\tDownloading the Wip Status Sheet..." );
                        log( "\tDownloading the Wip Status Sheet..." );
                        AdaptorUtils.saveAsBinaryFile( bfReader, m_dataOutputDir, FILE_NAME_WIP_STATUS, FILE_EXTN_CSV,true );
                        if ( m_adaptor_id > 0 )
                        {
                            AdaptorRunInfo.saveAdaptorFileInfo( m_adaptor_id , FILE_NAME_WIP_STATUS, FILE_EXTN_CSV, StringUtils.formatDateandTime(DateUtil.getFormattedTimeStamp() )) ;
                        }
                    }
                    else
                    {
                        log( "Could not save Lot Status Sheet from Buffer Reader" );
                        throw new ScalarException( "Could not save Wip Status Sheet from Buffer Reader" );
                    }
                }
                else
                {
                    log( "Could not create response object of Wip Status Sheet" );
                    throw new ScalarException( "Could not create response object of Wip Status Sheet" );
                }

                // For DownLoding the Shipment Information
               rsp = requestShippingReport( connection );

                if( rsp != null )
                {
                    bfReader = new BufferedInputStream( rsp.getInputStream()  );
                    if( bfReader != null )
                    {
                        System.out.println( "\tDownloading the Shipment info Sheet..." );
                        log( "\tDownloading the Shipment info Sheet..." );
                        AdaptorUtils.saveAsBinaryFile( bfReader, m_dataOutputDir, FILE_NAME_SHIP_STATUS, FILE_EXTN_CSV,true );
                        if ( m_adaptor_id > 0 )
                        {
                            AdaptorRunInfo.saveAdaptorFileInfo( m_adaptor_id , FILE_NAME_SHIP_STATUS, FILE_EXTN_CSV, StringUtils.formatDateandTime(DateUtil.getFormattedTimeStamp() )) ;
                        }
                    }
                    else
                    {
                        log( "Could not save Dynamic Ship Status Sheet from Buffer Reader" );
                        throw new ScalarException( "Could not save Ship Status Sheet from Buffer Reader" );
                    }
                }
                else
                {
                    log( "Could not create response object of Ship Status Sheet" );
                    throw new ScalarException( "Could not create response object of Ship Status Sheet" );
                }
                
                // Logging out from VIS WEB SITE
                logout( connection );
                System.out.println( "\nDone..." );
                log( "\nDone..." );
                bfReader = null;
            }
            else
            {
                log( "Could not able to get the Connection to web site" );
                throw new ScalarException( "Could not able to get the Connection to web site" );
            }
        }
        catch(Exception e )
        {
            AdaptorUtils.removeOldFiles( m_dataOutputDir, m_adaptorLogger);
            AdaptorRunInfo.updatedAdaptorStatus( CONSTANT_FAILURE, m_adaptor_id );
            System.out.println("Exception while trying to connect and read data from "+HOST +" site: " + e);
            e.printStackTrace();
            throw e;
        }
    }

    private HTTPConnection login( String host, int port, String username, String password ) throws Exception
    {
        byte[] data         = new byte[1024];
        HTTPResponse    rsp = null;

        HTTPConnection conn = new HTTPConnection( PROTOCOL_HTTP, host, port );
        CookieModule.setCookiePolicyHandler( null );
        HTTPConnection.addDefaultModule( CookieModule.class, -1 );

        NVPair defaultHeaders[] = new NVPair[ 8 ];
        defaultHeaders[ 0 ] = new NVPair( "Accept", "*/*" );
        defaultHeaders[ 1 ] = new NVPair( "Referer", "http://" + host );
        defaultHeaders[ 2 ] = new NVPair( "Accept-Language", "en-us" );
        defaultHeaders[ 3 ] = new NVPair( "Content-Type", "application/x-www-form-urlencoded" );
        defaultHeaders[ 4 ] = new NVPair( "Proxy-Connection", "Keep-Alive" );
        defaultHeaders[ 5 ] = new NVPair( "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)" );
        defaultHeaders[ 6 ] = new NVPair( "Host", host );
        defaultHeaders[ 7 ] = new NVPair( "Pragma", "no-cache" );

        conn.setDefaultHeaders( defaultHeaders );

        rsp  = conn.Get( "/" );

        NVPair[] formData = new NVPair[ 4 ];
        formData[ 0 ] = new NVPair( "method", "login" );
        formData[ 1 ] = new NVPair( "account", username );
        formData[ 2 ] = new NVPair( "password", password );
        formData[ 3 ] = new NVPair( "submit", "&nbsp;&nbsp;Login&nbsp;&nbsp;");

        System.out.print( "\nTrying to Logging in......" );
        log( "\nTrying to Logging in......" );

        rsp  = conn.Post( "/online/login.do", formData );
              
        log("rsp.getEffectiveURI() = " + rsp.getEffectiveURI() );

        /*while ( rsp.getInputStream().read( data ) != -1 )
        {
        	log( new String( data ) );
        }*/
        
        if ( rsp.getEffectiveURI().getQueryString() != null && ( rsp.getEffectiveURI().getQueryString().indexOf("online/login.do") != -1
                || rsp.getEffectiveURI().getQueryString().indexOf("method=list&previousPage=login.do") != -1 || rsp.getEffectiveURI().getQueryString().indexOf("method=changePassword" ) != -1 ) )
        {
            log( "\n\nLogin failed.. response from server: Password was Expired, Please Reset" );
            throw new ScalarException( "\n\nLogin failed.. Password was Expired, Please Reset " );
        }

        log( "Done." );
        return conn;
    }

    private HTTPResponse requestWipStatusReport( HTTPConnection conn) throws Exception
    {
        byte[] data         = new byte[1024*2];
        HTTPResponse rsp    = null;

        System.out.println( "\t\nSubmitting the request for Wip Staus......" );
        log( "\tSubmitting the request for Wip Staus......" );

        rsp = conn.Get( GET_WIP_STATUS );
                
        /*while ( rsp.getInputStream().read( data ) != -1 )
        {
            log(new String(data));
        }*/

		String  downLoadCSVURL = "/online/download.do?fabCode=&proxy_filter_fabCode=&customerPoNumber=&visPartId=&customerPartId=&visLotNumber=&wsDate=&currentStage=&stageInTime=&wipQuantity=&wipStatus=&layerNumber=&stayDay=&projectedDate=&commitedDate=&shipDate=&shipQuantity=&stageNo=&method=downloadWipDocument&pageSize=100&id=0&visLotNumberData=&extendLayout=Y&commitDateEnd=&companyCode="+m_accountNo +"&commitDateStart=&displayedColumns=fab_code%2Ccust_po_no%2Cvis_part_id%2Ccust_part_id%2Cvis_lot_no%2Cws_date%2CcurrentStageLinks%2Cstage_in_time%2Cwip_qty%2Cwip_status%2Clayer_no%2Cstay_day%2Cprojected_date%2Ccommit_date%2Cship_date%2Cship_qty%2Cstage_no&Format=csv&h=" +m_accHashValue ;

        /*while ( rsp.getInputStream().read( data ) != -1 )
        {
            log(new String(data));
        }*/
        
        rsp = conn.Get( downLoadCSVURL );

      
        return rsp;
    }

    private HTTPResponse requestRealTimeWipStatusReport( HTTPConnection conn) throws Exception
    {
        byte[] data         = new byte[1024*2];
        HTTPResponse rsp    = null;

        System.out.println( "\t\nSubmitting the request for Real Time Wip Staus......" );
        log( "\tSubmitting the request for Real Time Wip Staus......" );

        rsp = conn.Get( GET_REAL_WIP_STATUS );

        /*while ( rsp.getInputStream().read( data ) != -1 )
        {
            log(new String(data));
        }*/
        
       String downLoadCSVURL = "/online/download.do?fabCode=&proxy_filter_fabCode=&visPartId=&visLotNumber=&wsQuantity=&wsDate=&currentStage=&wipQuantity=&wipStatus=&componentId=&stageNo=&method=downloadRtwDocument&pageSize=100&id=0&visLotNumberData=&customerPartId=&companyCode="+m_accountNo +"&displayedColumns=fab_code%2Cvis_part_id%2Cvis_lot_no%2Cws_qty%2Cws_date%2CcurrentStageLinks%2Cwip_qty%2Cwip_status%2Ccomponent_id%2Cstage_no&Format=csv&h="+m_accHashValue;

        //rsp = conn.Get( getQueryURL );
        /*while ( rsp.getInputStream().read( data ) != -1 )
        {
            log(new String(data));
        }*/
        rsp = conn.Get( downLoadCSVURL );


        return rsp;
    }


    private HTTPResponse requestShippingReport( HTTPConnection conn) throws Exception
    {
        byte[] data         = new byte[1024];
        HTTPResponse rsp = null;

        System.out.println( "\t\nSubmitting the request for Shipping Info......" );
        log( "\tSubmitting the request for Shipping Info......" );

        rsp = conn.Get( GET_SHIP_STATUS );

        Calendar calendar = Calendar.getInstance();
        String toDate = StringUtils.formatDateToString( calendar.getTime(), "MM/dd/yyyy" );
        calendar.add( Calendar.DATE, -15 );
        String fromDate = StringUtils.formatDateToString( calendar.getTime(), "MM/dd/yyyy" );

        String downLoadCSVUrl = "/online/download.do?invoiceDate=&invoiceNumber=&customerPoNumber=&customerPartId=&visLotNumber=&shipQuantity=&um=&waferId=&shipTo=&fabCode=&proxy_filter_fabCode=&method=downloadSnDocument&pageSize=15&id=0&displayedColumns=invoice_date%2CinvoiceNumberLinks%2Ccust_po_number%2Ccust_part%2Clot_number%2Cship_qty%2Cum%2Cwafer_no%2Cship_to%2Cfab_code&companyCode="+m_accountNo +"&visPartId=&invoiceDateEnd="+toDate+"&invoiceDateStart="+fromDate+"&Format=csv&h="+m_accHashValue;
                           
        rsp = conn.Get( downLoadCSVUrl );
        /*while ( rsp.getInputStream().read( data ) != -1 )
        {
            System.out.println( new String( data ) );
        }*/
        return rsp;
    }

    private void logout( HTTPConnection conn ) throws Exception
    {
        try
        {
            System.out.print( "\n Logging out... " );
            log( "\n Logging out... " );
            HTTPResponse rsp = conn.Get( LOG_OUT );
            System.out.println( "Successfully logged out from VIS Site" );
            log( "Successfully logged out from VIS Site" );

            conn = null;
            rsp = null;
        }
        catch ( Exception ignore )
        {
            System.out.println( "Exception Occuered While Logging Out From VIS Site" + ignore);
            throw ignore;
        }
    }
       
    private void log( String message )
    {
        if ( message == null ) return;

        if ( m_adaptorLogger != null )
        {
            synchronized ( m_adaptorLogger )
            {
                m_adaptorLogger.logDebug( message + LINE_SEPARATOR );
            }
        }
        else
        {
            System.out.println( message );
        }
    }

}
